<template>
  <van-sticky :offset-top="44">
    <div class="header">
      <van-search v-model="queryData.customerName" shape="round" placeholder="请输入公司名称" @update:model-value="onSearch" />
      <div class="add" @click="addVisiting">新增</div>
      <!-- <div class="add" @click="toJsapi">去JSAPI</div> -->
    </div>
    <van-dropdown-menu active-color="#5a9df8">
      <van-dropdown-item v-model="queryData.visitType" :options="crmVisitTypeOption" @change="onSearch" />
      <van-dropdown-item :title="visitTimeTitle" ref="visitTime">
        <div style="padding: 10px">
          <div style="overflow-y: auto;height: 500px">
            <van-calendar
              :show-title="false"
              :poppable="false"
              color="#5a9df8"
              :show-confirm="false"
              :min-date="minDate"
              :default-date="defaultDate"
              type="range"
              :allow-same-day="true"
              style="height: 390px"
              @confirm="onDateConfirm"
            >
            </van-calendar>
          </div>
          <van-button round block color="#67c23a" @click="clearVisitTime"> 重置 </van-button>
        </div>
      </van-dropdown-item>
      <van-dropdown-item
        v-if="userInfo.isLeader == 'Y'"
        v-model="queryData.ownerUserId"
        :options="ownerUserOption"
        @change="onSearch"
      />
    </van-dropdown-menu>
  </van-sticky>

  <!-- <div class="padding-md"> -->
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh" style="margin-top: 44px">
    <van-list v-model="loading" :finished="finished" finished-text="" @load="onLoad">
      <div v-for="(item, index) in dataList" :key="index" class="list-wrap flex-start" @click="clickVisiting(item)">
        <div class="img-icon">
          <!-- <img src="http://shanzuwang-test.oss-cn-shanghai.aliyuncs.com/upload/20241121/a1914c700b4475f06b772131e682ddc9.jpg" style="width: 40px" /> -->
          <img v-if="item.enclosureList" :src="item.enclosureList[0].value" style="width: 40px" />
          <van-icon v-else name="photo" size="34px" color="#ccc" />
        </div>
        <div style="flex: 1">
          <div class="flex-between line">
            <div class="title van-ellipsis" style="width: 100px">{{ item.customerName }}</div>
            <van-tag v-if="item.visitType" type="success" plain>{{
              valueTolabel1(item.visitType, crmVisitTypeOption)
            }}</van-tag>
          </div>
          <div class="flex-between">
            <div class="lable">单据号：</div>
            <div class="value">{{ item.sn }}</div>
          </div>
          <div class="flex-between">
            <div class="lable">拜访日期：</div>
            <div class="value">{{ item.visitTime }}</div>
          </div>
          <div class="flex-between">
            <div class="lable">拜访事由：</div>
            <div class="value">{{ item.visitReason }}</div>
          </div>
          <div class="flex-between">
            <div class="lable">创建人：</div>
            <div class="value">{{ item.ownerUser }}</div>
          </div>
        </div>
      </div>
    </van-list>
    <van-empty v-if="!dataList.length" description="暂无数据" />
  </van-pull-refresh>
  <!-- </div> -->
</template>

<script>
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { getBusinessVisitList, getUserPageList } from '@/api/businessOpportunity'
import { getDictionary } from '@/api/dictionary'
import { getAssetsImages, valueTolabel } from '@/utils'
import { reactive, toRefs, onBeforeMount, onActivated, computed, nextTick } from 'vue'
import { ref } from 'vue'
export default {
  name: 'visit',
  setup(props, cxt) {
    const visitTime = ref(null)
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const getAssetsImages1 = getAssetsImages
    const valueTolabel1 = valueTolabel
    const userInfo = computed(() => {
      return store.getters['userInfo']
    })
    const state = reactive({
      queryData: {
        customerName: '',
        visitType: '',
        visitTimeRange: '',
        ownerUserId: '',
        current: 1,
        size: 1000
      },
      visitTimeTitle: '拜访日期',
      defaultDate: [new Date(), new Date()],
      minDate: new Date(2024, 0, 1),
      crmVisitTypeOption: [],
      ownerUserOption: [],
      loading: false,
      disabled: false,
      finished: false,
      refreshing: false,
      hasNextPage: false,
      total: 0,
      dataList: []
    })
    const getList = () => {
      getBusinessVisitList(state.queryData)
        .then((res) => {
          if (state.refreshing) {
            state.dataList = []
            state.refreshing = false
          }
          const { records, total } = res
          state.hasNextPage = false
          state.dataList = records
          state.total = total
          state.finished = !state.hasNextPage
        })
        .catch(() => {
          state.refreshing = false
          state.finished = true
        })
    }
    const onSearch = () => {
      getList()
    }

    const onLoad = () => {
      if (state.hasNextPage) {
        state.queryData.current++
        getList()
      }
    }
    // 下拉刷新
    const onRefresh = () => {
      // 清空列表数据
      state.finished = false
      state.dataList = []

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      // state.loading = true
      state.queryData.current = 1
      state.hasNextPage = false
      getList()
    }
    const formatDate = (date, sigal = '/') =>
      `${date.getFullYear()}${sigal}${date.getMonth() + 1}${sigal}${date.getDate()}`
    const onDateConfirm = (values) => {
      const [start, end] = values
      state.queryData.visitTimeRange = `${formatDate(start, '-')},${formatDate(end, '-')}`
      state.visitTimeTitle = `${formatDate(start)} - ${formatDate(end)}`
      getList()
      setTimeout(() => {
        visitTime.value.toggle()
      }, 800)
    }
    const clearVisitTime = () => {
      state.queryData.visitTimeRange = ''
      state.visitTimeTitle = '拜访日期'
      state.defaultDate = [new Date(), new Date()]
      getList()
      visitTime.value.toggle()
    }
    const addVisiting = () => {
      router.push({ path: './addVisiting' })
    }
    const toJsapi = () => {
      router.push({ path: './jsApi' })
    }

    const clickVisiting = (item) => {
      router.push({ path: './addVisiting', query: { id: item.id } })
    }

    const initDictionary = (code) => {
      getDictionary({ code }).then((res) => {
        const newDic = transOption(res)
        if (code == 'crm_visit_type') {
          const first = { text: '拜访类型', value: '' }
          newDic.unshift(first)
          state.crmVisitTypeOption = newDic
        }
      })
    }
    const getUserOption = () => {
      getUserPageList().then((res) => {
        const newDic = transOption(res, { value: 'realName', key: 'id' })
        const first = { text: '创建人', value: '' }
        newDic.unshift(first)
        state.ownerUserOption = newDic
      })
    }

    const transOption = (data, formatter = { value: 'dictValue', key: 'dictKey' }) => {
      const newDate = []
      data.map((item) => {
        const obj = {
          text: item[formatter.value],
          value: item[formatter.key]
        }
        newDate.push(obj)
      })
      return newDate
    }

    onBeforeMount(() => {
      const { salerId, visitType } = route.query
      if (visitType) {
        state.queryData.visitType = visitType
      }
      if (salerId) {
        state.queryData.ownerUserId = salerId
      }
      initDictionary('crm_visit_type')
      if (userInfo.value.isLeader == 'Y') {
        getUserOption()
      } else {
	      state.queryData.ownerUserId = userInfo.value.id
      }
      getList()
    })

    onActivated(() => {
      getList()
    })

    return {
      ...toRefs(state),
      visitTime,
      userInfo,
      onLoad,
      onRefresh,
      addVisiting,
      toJsapi,
      clickVisiting,
      onSearch,
      onDateConfirm,
      clearVisitTime,
      getAssetsImages1,
      valueTolabel1
    }
  }
}
</script>
<style lang="less" scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  .van-search {
    flex: 1;
    padding-right: 0;
  }
  .add {
    padding-left: 10px;
    padding-right: 10px;
    color: #5a9df8;
    font-size: 14px;
  }
}

.padding-md {
  padding: 0 15px 15px;
}
</style>
